/*
 * fupload 1.0
 * Copyright (c) 2013 黄奕雄
 * Date: 2014-04-4
 */

(function(factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery','./jquery.ui.widget','./jquery.iframe-transport','./jquery.fileupload'], factory);
    } else {
        factory(window.jQuery);
    }
}(function($) {
  if (typeof define === 'function' && define.amd) {
        var csss = ['./fileupload/css/jquery.fileupload.css'];
    
        for(var i=0;i<csss.length;i++){
            var css=csss[i];
            css = require[require.toUrl ? 'toUrl' : 'resolve'](css);
            css = '<link rel="stylesheet" href="' + css + '" />';
            $('base')[0] ? $('base').before(css) : $('head').append(css);
       }       
    }

    $.fn.fupload = function(o) {
        var defaults = {
            bw    : 178,
            bh    : 43,
            size  : '2M',
            img   : 'button_up.png',
            path  : 'YnVzaW5lc3M=', //business
            input : 'photo',
            uid   : 0,
            max   : 2,
            extension : '*.gif; *.jpg;*.jpeg;*.bmp',
            auto  : true,
            btxt  : '',
            multi :true,
            style :'pic', //pic:图片，file:文件
            icoh  : null,
            orderid:'',
            do    : 'upload',
			dev   : '',
			val_id:'',
            imgType:'',
            operator:'manage'
        };


        return this.each(function() { 
            var t=$(this);
            var opts = $.extend({}, defaults, o);
            if(t.data('rel')){
                eval('var rel={'+ t.data('rel')+'}');
                opts = $.extend({},opts, rel);
            }
            var objid = t.attr("id");
            var url = FILEHOST;
            var d={
                picarea:$('#'+objid+'-queue'),
                mover:function(a){
                    $(a).delegate('.f-item','mouseenter',function(e){
                        $(this).find('i,a').fadeIn(200);
                        $(this).find('span').show().stop(true).animate({'opacity':.5},200);
                        d.del($(this).find('i'));
                        d.sethome($(this).find('a'));
                    });
                    $(a).delegate('.f-item','mouseleave',function(e){
                        $(this).find('i,a:not(.active)').fadeOut(200);
                        $(this).find('span').stop(true).animate({'opacity':0},200,function(){$(this).hide();});
                    });
                },
                del:function(a){
                    $(a).off('click').on('click',function(e){
                        var b=$(this);
						b.closest('.upload-area').find('.upload_add').show();
                        b.closest('.f-item').fadeOut(function(){
                            $(this).remove();
                            d.check();
                        });
                        //回调函数处理
                        if($.isFunction(opts.delFn)){ opts.delFn();}
                    });
                },
                sethome:function(a){
                    $(a).click(function(){
                        var home_img = $(this).data('rel');
                        $('#home_img').val(home_img);
                        $(this).addClass('active').parent('.f-item').siblings().find('.sethome').removeClass('active').hide();
                    });
                },
                check:function(){
                    if(opts.max==1) {
                       return true;
                    }else{
                        if(d.picarea.find('.f-item').length>=opts.max){
                            $('#'+objid).parent().hide().prop("disabled",true);
                            return false;
                        }else{
                            $('#'+objid).parent().show().prop("disabled",false);
                            return true;
                        }
                    }
                },
                init:function(){
                    d.mover(d.picarea);
                    d.del(d.picarea.find('.f-item i'));
                    d.check();
                }
            };
            d.init();
            t.fileupload({
                url: url,
                forceIframeTransport: true,
                formData:{'do':opts.do,'do_type':opts.path,'operator':opts.operator,'input_field':opts.input,'uid':opts.uid},
                dataType: 'html',
                processData: true,
                contentType: true,
                cache: true,
                redirect:ADMINHOST+'/Public/jqueryuploadredirect?%s',
                done: function (e, data) {
                    var result=data.result;

                    if(result){
                        result=$.parseJSON(result);
                        if(result.status==1){
                            if(opts.dev=='mobile'){
                                $.each(result.files,function(i,j){
                                    if(typeof j.midUrl != "undefined"){
                                        var url = j.midUrl;
                                    } else if(typeof j.smallUrl != "undefined"){
                                        var url = j.smallUrl;
                                    } else if(typeof j.bigUrl != "undefined") {
                                        var url = j.bigUrl;
                                    } else {
                                        var url = j.url;
                                    }

                                    if(opts.path=='ZWRpdG9y'){
                                        url = j.url;
                                    }else{
                                        url = j.bigUrl;
                                    }
                                    var dwarp=$('#'+objid).closest('.mobile');

                                    if(dwarp.find('.editbox').attr('data-type')=="add"){
                                        var li='<li><span class="info"><img src="'+url+'" alt="" /></span></li>';
                                        var index = dwarp.find('#pic_pos').val();
                                        if(index!=''){
                                            dwarp.find('.info-list ul li:eq('+index+')').before(li);
                                            dwarp.find('#pic_pos').val('');
                                        }else{
                                            dwarp.find('.info-list ul').append(li);
                                        }
                                    }else{
                                        var li='<img src="'+url+'" alt="" />';
                                        var edit=dwarp.find('.info-list > ul > li[edit]');

                                        edit.find('.info').html(li);
                                        edit.removeAttr('edit');
                                    }

                                });
                                t.parent().hide();
                            }else if(opts.dev=='spec'){
                                $.each(result.files,function(i,j){
                                    if(typeof j.midUrl != "undefined"){
                                        var url = j.midUrl;
                                    } else if(typeof j.smallUrl != "undefined"){
                                        var url = j.smallUrl;
                                    } else if(typeof j.bigUrl != "undefined") {
                                        var url = j.bigUrl;
                                    } else {
                                        var url = j.url;
                                    }

                                    var img=''
                                        +'<img src="'+j.bigUrl+'" alt="" style="float:left;height:28px;margin:0 5px;" />'
                                        +'<a href="javascript:;" class="fl del">删除</a>'
                                        +'<input name="'+opts.input+'[]" type="hidden" value="'+j.savename+'" />';

                                    var ids =t.attr('data-img').split(',');
                                    var formatbox = $('.format[data-cid="'+ids[0]+'"]');
                                    var sitem=formatbox.find('.item[data-id="'+ids[1]+'"]');
                                    formatbox.find('.upload-color tr[data-id="'+ids[1]+'"] .fitem').html(img);

                                    eval('var rel={'+sitem.data('rel')+'}');
                                    rel.img=j.savename;
                                    var tempv=[];
                                    $.each(rel,function(m,n){
                                        tempv.push(m+":'"+n+"'");
                                    });
                                    sitem.find('.itemv').val(tempv.join(','));
                                    sitem.data('rel',tempv.join(','));
                                    sitem.find('.checkInput').trigger('change');
                                });
                            } else {
                                $.each(result.files,function(i,j){
                                    if(typeof j.midUrl != "undefined"){
                                        var url = j.midUrl;
                                    } else if(typeof j.smallUrl != "undefined"){
                                        var url = j.smallUrl;
                                    } else if(typeof j.bigUrl != "undefined") {
                                        var url = j.bigUrl;
                                    } else {
                                        var url = j.url;
                                    }

                                    var type = j.type;
                                    var a = type.split("/");
                                    if(a[0] != 'image'){
                                        url = PUBLIC+'/admin/images/txt.gif';
                                    }

                                    if(opts.imgType == 'big'){
                                        url = j.bigUrl;
                                    }
                                    if(opts.imgType == 'wx'){
                                        var obj= $('.dg-picture .bd');

                                        var picitem='<div class="item"><a href="javascript:;">'
                                            +'<div class="pic">'
                                            +'<input type="hidden" value="'+ j.url+'" name="pic">'
                                            +'<img width="80" height="80" src="'+ j.url+'">'
                                            +'<em class="icon-select"></em>'
                                            +'</div>'
                                            +'<div class="name">'+j.savename+'</div>'
                                            +'</a>'
                                            +'</div>';
                                        obj.append(picitem);
                                    }else if(opts.imgType == 'wx_upload'){
                                        var obj = opts.back;
                                        var str = '<div class="show-img">';
                                        var imgSrc = j.url;
                                        str +='<img width="80" height="80" src="'+imgSrc+'">';
                                        var arr = imgSrc.split('/').pop().split('.');
                                        var imgName = arr[0]+'.'+arr[1];
                                        str +='<input type="hidden" name="imgName" value="'+imgName+'" />';
                                        str +='<a href="javascript:void(0);" class="blue ml10 del-show-img">删除</a>';
                                        str +='</div>';
                                        obj.find('.uploadBox').hide();
                                        obj.append(str);
                                    }
                                    var shtml='<img img_name="'+j.name+'" src="'+url+'"/><span></span><i title="删除该图片"></i><input name="'+opts.input+'[]" type="hidden" value="'+j.savename+'" />'
                                    //if(opts.icoh){
                                    //  shtml += '<a class="sethome" data-rel="'+j.savename+'" href="javascript:void(0)" title="设为默认"/></a>';
                                    //}
                                    //回调函数处理
                                    if($.isFunction(opts.fn)){ opts.fn(url);}

                                    d.picarea.find('.load').eq(i).html(shtml).removeClass('load');
                                });
                                d.mover(d.picarea);
                                d.check();

                                if(opts.max == d.picarea.find('.f-item').length){
                                    if(opts.max==1){
                                        d.picarea.find('.f-item').css('margin-right','0');
                                    }
                                    d.picarea.siblings().hide();
                                }
                            }
                        } else {
                            ZENG.msgbox.show(result.info, 5,2000);
							d.picarea.find('.f-item').remove();
                        }
                    }
                },
				submit: function (e, data) {
					for(var m=1;m<=data.files.length;m++){
                        if(!d.check()){
							break;
						}
						var _item=$('<div class="f-item load"><div class="loadimg"></div></div>');
                        if(opts.max>1) {
                            d.picarea.append(_item);
                        }else{
                            d.picarea.html(_item);
                        }
					}
				},
                change: function (e, data){
                    //手机
                    if(opts.dev=='mobile'){
                        var dwarp=$('#'+objid).closest('.mobile');
                        dwarp.find('#upload_pic').hide().parents('.editWarp').siblings('.info-list').show();
                        dwarp.find('#upload_pic #fileupload').attr('multiple',true);
                    }

                    var snum=data.files.length;
                    var cnum=opts.max-d.picarea.find('.f-item').length;
                    if(opts.max==1) return true;
                    if(d.picarea.find('.f-item').length==0 && snum>opts.max){
                        alert('对不起，您最多可以上传'+opts.max+'张');
                        return false;
                    }
                    if(snum>cnum){
                        alert('对不起，您最多还可以上传'+cnum+'张');
                        return false;
                    }
                },
                fail: function (e, data) {
                    var result = data.files;
                    var xhr=data.jqXHR;
                    var str=data.errorThrown;
                    if(xhr.status==413){
                        str='只允许上传文件最大'+opts.size;
                    }
                    $.each(result,function(i,j){
                        alert(j.name+'\n上传失败：'+str);
                        d.picarea.find('.load').eq(i).remove();
                        d.check();
                    });
                },
                progressall: function (e, data) {
					$('#progress').show();
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    $('#progress .progress-bar').css(
                        'width',
                        progress*2 + 'px'
                    );
					$('#progress .progress_num').html(progress + '%');
					if(progress==100) $('#progress').hide();
                }
            }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
        });
    };
}));